﻿namespace K9Nano.Updater.Pipes;

public abstract class UpdatePipeBase : IUpdatePipe
{
    public string PipeName { get; protected set; }

    public virtual async Task InvokeAsync(UpdateContext context, CancellationToken cancellation = default)
    {
        try
        {
            if (!CanInvoke(context))
            {
                context.LogDebug("跳过执行");
                return;
            }
            context.LogInformation("开始执行");
            await InvokeCoreAsync(context, cancellation);
            context.LogInformation("执行完成");
        }
        catch (TaskCanceledException)
        {
            context.LogError("任务被取消");
            TryRollback();
        }
        catch (Exception ex)
        {
            context.LogError(ex, "任务失败");
            TryRollback();
        }
        context.ReportProgress(100);
        return;

        void TryRollback()
        {
            try
            {
                Rollback(context);
            }
            catch (Exception ex)
            {
                context.LogError(ex, "回滚失败");
            }
        }
    }

    protected abstract Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation);

    protected virtual bool CanInvoke(UpdateContext context)
    {
        return !context.Terminated;
    }

    protected virtual void Rollback(UpdateContext context)
    {
    }
}